package com.tools.function.sdcard;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import com.tools.function.R;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class SDMainActivity extends BaseActivity implements OnClickListener {

	private ListView listView;

	private ImageButton returnBtn;

	private TextView titleView;
	private int check = 0;// 创建文件的标志

	private LocalFileAdapter adapter;

	private Map<String, String> map = null;// 这个用来保存复制和粘贴的路径

	private File root;

	private List<File> list;
	private View view;
	private LinearLayout layout;
	private MyButtion addButtion, searchButtion, menuButtion;

	// path的堆栈
	private static Stack<String> pathStack;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		view = LayoutInflater.from(SDMainActivity.this).inflate(R.layout.local_file_dialog, null);
		setContentView(view);
		String storageState = Environment.getExternalStorageState();

		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
		} else {
			finish();
		}
		initView();

	}

	/**
	 * 查询调用方法
	 */
	public void searchData(String path) {
		searchViewData(path);
		titleView.setText(path);
	}

	/**
	 * 查询view的数据
	 */
	public void searchViewData(final String path) {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {

				try {
					list = FileUtil.getFileListByPath(path);
				} catch (Exception e) {
					return false;
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);

				if (result) {

					adapter.setFiles(list);

					adapter.setSelectedPosition(-1);

					adapter.notifyDataSetChanged();

				} else {
					Toast.makeText(SDMainActivity.this, "查询失败", Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	/**
	 * 初始化视图
	 */
	private void initView() {

		layout = (LinearLayout) findViewById(R.id.local_File_lin);

		listView = (ListView) findViewById(R.id.local_File_drawer);

		adapter = new LocalFileAdapter(this, list);

		listView.setAdapter(adapter);

		map = new HashMap<String, String>();

		listView.setOnItemClickListener(new DrawerItemClickListener());
		registerForContextMenu(listView);// 注册一个上下文菜单

		returnBtn = (ImageButton) findViewById(R.id.local_File_return_btn);

		returnBtn.setOnClickListener(this);

		titleView = (TextView) findViewById(R.id.local_File_title);
		addButtion = (MyButtion) findViewById(R.id.myButtion1);
		searchButtion = (MyButtion) findViewById(R.id.myButtion2);
		menuButtion = (MyButtion) findViewById(R.id.myButtion3);
		addButtion.setOnClickListener(this);
		searchButtion.setOnClickListener(this);
		menuButtion.setOnClickListener(this);
		searchData(root.getAbsolutePath());

		addPath(root.getAbsolutePath());

	}

	/*
	 * 创建一个上下文菜单
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.file_item, menu);

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	/*
	 * 上下文菜单选项
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		final int position = info.position;
		final List<File> list = adapter.getFiles();// 得到文件的list
		String path = list.get(position).getPath();
		System.out.println("-----" + path + "-------");
		switch (item.getItemId()) {
		case R.id.copy:
			// 复制目录
			System.out.println("复制目录");
			String fromPath = list.get(position).getPath();
			System.out.println(list.get(position).getPath());
			map.put("fromPath", fromPath);
			System.out.println("最" + getLastPath());

			System.out.println(map.get("fromPath"));
			String name = map.get("fromPath").substring(
					getLastPath().length() + 1, map.get("fromPath").length());
			map.put("name", name);
			System.out.println(name);
			break;
		case R.id.stick:
			System.out.println("粘贴");
			if (!map.isEmpty()) {
				File file = new File(map.get("fromPath"));
				if (file.isFile()) {
					FileUtil.copyFile(file, map.get("name"), list.get(position));
					File tFile = new File(list.get(position), map.get("name"));
					if (tFile != null && tFile.exists()) {
						Toast.makeText(SDMainActivity.this, "复制文件成功",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(SDMainActivity.this, "复制文件失败",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					FileUtil.copyFolder(file,
							new File(list.get(position), map.get("name")));
					File dFile = new File(list.get(position), map.get("name"));
					if (dFile != null && dFile.exists()) {
						Toast.makeText(SDMainActivity.this, "复制目录成功",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(SDMainActivity.this, "复制目录失败",
								Toast.LENGTH_SHORT).show();
					}
				}
				map.clear();// 清空
				searchData(getLastPath());
			} else {
				Toast.makeText(SDMainActivity.this, "还没有选中要复制的文件或目录",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.cancel:
			if (!map.isEmpty()) {
				map.clear();
				Toast.makeText(SDMainActivity.this, "已取消", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(SDMainActivity.this, "没有复制的目录或文件",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.del:
			final CustomDialog customDialog = new CustomDialog(
					SDMainActivity.this, getCurrentFocus());
			customDialog.setTitle("提示");
			customDialog.setMessage("确定删除?");
			customDialog.setPositiveButton("确定", new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					customDialog.dismiss();
					File dir = list.get(position);
					if (dir.isFile()) {
						dir.delete();
					} else {
						FileUtil.deleteDir(list.get(position));
					}
					if (dir == null || !dir.exists()) {
						Toast.makeText(SDMainActivity.this, "删除成功",
								Toast.LENGTH_SHORT).show();
						searchData(titleView.getText().toString());
					} else {
						Toast.makeText(SDMainActivity.this, "删除失败",
								Toast.LENGTH_SHORT).show();
					}
				}
			});
			customDialog.setNegativeButton("取消", new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					customDialog.dismiss();
				}
			});
			customDialog.show();
			break;
		case R.id.mod:
			// 重命名
			Builder builder = new Builder(
					SDMainActivity.this);
			builder.setTitle("提示对话框");
			View view = LayoutInflater.from(SDMainActivity.this).inflate(
					R.layout.mydialog, null);
			builder.setView(view);
			final EditText toEditText = (EditText) view
					.findViewById(R.id.rename_edit);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							if (FileUtil.renameFile(list.get(position),
									getLastPath(), toEditText.getText()
											.toString())) {
								Toast.makeText(SDMainActivity.this, "重命名成功",
										Toast.LENGTH_SHORT).show();
								searchData(getLastPath());
							}
							{
								Toast.makeText(SDMainActivity.this, "重命名失败",
										Toast.LENGTH_SHORT).show();
							}
							dialog.dismiss();
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});
			builder.create().show();

			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	/**
	 * 添加路径到堆栈
	 * 
	 * @param path
	 */
	public void addPath(String path) {

		if (pathStack == null) {
			pathStack = new Stack<String>();
		}

		pathStack.add(path);
	}

	/**
	 * 获取堆栈最上层的路径
	 * 
	 * @return
	 */
	public String getLastPath() {
		return pathStack.lastElement();
	}

	/**
	 * 移除堆栈最上层路径
	 */
	public void removeLastPath() {
		pathStack.remove(getLastPath());
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			adapter.setSelectedPosition(position);

			selectItem(position);
		}
	}

	private void selectItem(int position) {

		String filePath = adapter.getFiles().get(position).getAbsolutePath();

		String fileName = adapter.getFiles().get(position).getName();

		if (adapter.getFiles().get(position).isDirectory()) {
			searchData(filePath);
			addPath(filePath);
		} else if (adapter.getFiles().get(position).isFile()) {
			// 判断是否为文件
			FileUtil.openFile(SDMainActivity.this, fileName, adapter.getFiles()
					.get(position));
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.local_File_return_btn:
			if (getLastPath().equals(root.getAbsolutePath())) {
				return;
			}
			removeLastPath();
			searchData(getLastPath());

			break;
		case R.id.myButtion1:
			System.out.println("------添加-------");
			AlertDialog alertDialog = oncreateAlertDialog();
			alertDialog.show();
			break;
		case R.id.myButtion2:
			System.out.println("-------搜索-------");
			break;
		case R.id.myButtion3:
			System.out.println("-------菜单--------");
			break;
		default:
			break;
		}

	}

	public AlertDialog oncreateAlertDialog() {
		Builder builder = new Builder(SDMainActivity.this);
		builder.setTitle("提示对话框");
		final View dialogView = LayoutInflater.from(SDMainActivity.this).inflate(R.layout.myadd_dialog, null);
		builder.setView(dialogView);
		final EditText toText = (EditText) dialogView.findViewById(R.id.add_file_dir);
		RadioGroup radioGroup = (RadioGroup) dialogView
				.findViewById(R.id.radioGroup1);
		radioGroup
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						switch (checkedId) {
						case R.id.file:
							check = 0;
							System.out.println(check);
							break;

						case R.id.dir:
							check = 1;
							System.out.println(check);
							break;
						}
					}
				});

		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (!toText.getText().toString().equals("")
						&& toText.getText().toString() != null) {
					// 创建目录或文件的方法
					FileUtil.createDirorFile(getLastPath(), toText.getText()
							.toString(), SDMainActivity.this, check);
				}
				searchData(getLastPath());
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		return builder.create();
	}

	@Override
	protected void onDestroy() {
		AppManager.getAppManager().finishActivity(this);
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			final CustomDialog customDialog = new CustomDialog(
					SDMainActivity.this, view);
			customDialog.setTitle("提示");
			customDialog.setMessage("确定退出吗?");
			customDialog.setPositiveButton("确定", new OnClickListener() {

				@Override
				public void onClick(View v) {
					customDialog.dismiss();
					AppManager.getAppManager().AppExit(SDMainActivity.this);
				}
			});
			customDialog.setNegativeButton("取消", new OnClickListener() {

				@Override
				public void onClick(View v) {
					customDialog.dismiss();
				}
			});
			customDialog.show();

		}
		return super.onKeyDown(keyCode, event);
	}
}
